<template>
  <div class="c-h">
    <img src="" class="c-w100" id="spreadImg" v-if="imgInfo != null" @touchstart="touchStartImg" @touchmove="touchEndImg" @touchend="touchEndImg" />
    <div class="canvasBox c-flex-row" v-if="imgInfo&&imgInfo.shareStyle==2">
      <div class="anvasContent c-p" id="canvas1">
        <img :src="$addXossFilter(imgInfo.shareCustomizeImage)" alt class="c-w100 c-h img-pe-none">
        <div v-if="imgInfo.shareCustomizeControl" class="customOne bgLocation">
          <div v-for="(item,index) in imgInfo.shareCustomizeControl" :key="index">
            <div v-if="item.type==3" :style="item" class="c-pa">
              <div class="c-flex-column c-aligni-center">
                <img :src="$addXossFilter(imgInfo.peopleAvatar)" alt class="headerImg120 c-brp50 img-pe-none">
                <p>{{imgInfo.nickname}}</p>
              </div>
            </div>
            <div v-if="item.type==2" :style="item" class="c-pa c-table">
              <span class="c-tableCell" :style="'vertical-align:'+item.verticalAlign">{{item.name}}</span>
            </div>
            <img v-if="item.type==1" class="c-pa" :src="$addXossFilter(imgInfo.qrcodeUrl)" alt :style="item">
          </div>
        </div>
      </div>
    </div>
    <loading-status-tem :noData="isInfo" :noDataText="'暂时还没有分享图片'"></loading-status-tem>
  </div>
</template>

<script>
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import { reportPageShareSuccess } from "@/utils/userTraceLog.js";
import { utilJs } from "@/utils/common.js"
let html2canvas = null;
export default {
  name: 'ExaminationSpread',
  components: {
    loadingStatusTem
  },
  props: [],
  beforeCreate() {

  },
  data() {
    return {
      paperMainId: -1,
      topicId: -1,
      imgInfo: null,
      isInfo: false,
      fromQr: 0,
      examinationInfo: null,
      isFromMutua: false,
      showVisitInlet:true,
      enableShowScore:1
    }
  },
  created() {
    utilJs.appShare(this);
  },
  mounted() {
    import(/* webpackChunkName: "html2canvas" */"@/utils/html2canvas.js").then(res => {
      html2canvas = res.default;
    })
  },
  computed: {

  },
  watch: {

  },
  methods: {
    touchStartImg() {
      clearTimeout(this._touchTimeCon);
      this._touchTimeCon = setTimeout(() => {
        reportPageShareSuccess(this._shareUrl);
      }, 250);
    },
    touchEndImg() {
      clearTimeout(this._touchTimeCon );
      this._touchTimeCon = null;
    },
    drawImg(imgDetail) {
      let that = this
      var c = document.createElement('canvas');
      c.width = 640;
      c.height = 1136;
      var ctx = c.getContext("2d");
      let imgBg = new Image();
      imgBg.crossOrigin = 'anonymous';
      imgBg.onload = function () {
        ctx.save();
        ctx.drawImage(imgBg, 0, 0, 640, 1136);

        let imgPeopleAvatar = new Image();
        imgPeopleAvatar.crossOrigin = 'anonymous';
        imgPeopleAvatar.onload = function () {
          ctx.save();
          ctx.strokeStyle = '#ffffff';
          ctx.lineWidth = 8;
          ctx.lineCap = "round";
          ctx.beginPath();
          ctx.arc(314, 118, 54, 0, 2 * Math.PI, false); //用于绘制圆弧context.arc(x坐标，y坐标，半径，起始角度，终止角度，顺时针/逆时针)
          ctx.stroke();
          ctx.closePath();
          ctx.save();
          ctx.arc(314, 118, 54, 0, 2 * Math.PI);
          ctx.clip();
          ctx.drawImage(imgPeopleAvatar, 260, 64, 108, 108);
          ctx.restore();

          let img1 = new Image();
          img1.crossOrigin = 'anonymous';
          img1.onload = function () {
            ctx.save();
            ctx.drawImage(img1, 110, 456, 420, 280);

            let img2 = new Image();
            img2.crossOrigin = 'anonymous';

            img2.onload = function () {
              ctx.save();
              ctx.drawImage(img2, 240, 824, 160, 160);
              // ctx.font = "36px Microsoft YaHei";
              // ctx.fillStyle = "#333333";

              // ctx.textAlign = 'center'
              // if (imgDetail.paperType == 1 || imgDetail.paperType == 2) {
              //   if (imgDetail.scoringMethod == 3) {
              //     ctx.fillText('我刚刚参加了测试，答对了', 320, 290);
              //     ctx.fillText(imgDetail.rightNum + '题的好成绩', 320, 336);
              //   } else if (imgDetail.scoringMethod == 2) {
               if (that.imgInfo.shareText) {
                ctx.font = "32px PingFangSC";
                ctx.fillStyle = "#333333";
                ctx.textAlign = 'center'
                if (that.imgInfo.shareText.length > 15) {
                  ctx.fillText(that.imgInfo.shareText.substring(0, 12), 320, 230);
                  ctx.fillText(that.imgInfo.shareText.substring(12, 20), 320, 270);
                } else {
                  ctx.fillText(that.imgInfo.shareText, 320, 230);
                }
              }
                  // if (that.isFromMutua && that.imgInfo.paperType == 3) {
                  //   ctx.fillText('我刚刚参加了个有趣的测试', 320, 290);
                  //   ctx.fillText('你也来试试！', 320, 336);
                  // } else if ((that.isFromMutua && that.imgInfo.isRemark == 6) || (that.isFromMutua && that.imgInfo.isHideScore == 1)) {
                  //   ctx.fillText('我刚刚参加了个测试，', 320, 290);
                  //   ctx.fillText('获得了好成绩', 320, 336);
                  // } else {
                  if (that.imgInfo.enableShowScore == 1 && that.imgInfo.isCheck == 1) {
                    ctx.font = "bolder 34px PingFangSC";
                    ctx.fillStyle = "#333333";
                    ctx.textAlign = 'center'
                    if (that.imgInfo.enablePeople == 0) {
                      ctx.fillText(imgDetail.totalpoins + '分', 320, 344);
                    } else {
                      ctx.fillText(imgDetail.totalpoins + '分', 180, 344);
                    }
                    ctx.font = "24px PingFangSC";
                    ctx.fillStyle = "#999999";
                    ctx.textAlign = 'center'
                    if (that.imgInfo.enablePeople == 0) {
                      ctx.fillText('得分', 320, 382);
                    } else {
                      ctx.fillText('得分', 180, 382);
                    }
                  }
                  if (that.imgInfo.enableShowScore == 1 && that.imgInfo.isCheck == 1 && that.imgInfo.enablePeople == 1) {
                    ctx.lineWidth = 2
                    ctx.strokeStyle = "#E8E8E8"
                    ctx.moveTo(320, 336)
                    ctx.lineTo(320, 376)
                    ctx.stroke();
                  }
                  if (that.imgInfo.enablePeople == 1) {
                    ctx.font = "bolder 34px PingFangSC";
                    ctx.fillStyle = "#333333";
                    ctx.textAlign = 'center'
                    if (that.imgInfo.enableShowScore == 1 && that.imgInfo.isCheck == 1) {
                      ctx.fillText(imgDetail.allTestMan + '人', 460, 344);
                    } else {
                      ctx.fillText(imgDetail.allTestMan + '人', 320, 344);
                    }
                    ctx.font = "24px PingFangSC";
                    ctx.fillStyle = "#999999";
                    ctx.textAlign = 'center'
                    if (that.imgInfo.enableShowScore == 1 && that.imgInfo.isCheck == 1) {
                      ctx.fillText('参与人', 460, 382);
                    } else {
                      ctx.fillText('参与人', 320, 382);
                    }
                  }
                // } else {
                //   ctx.fillText('我刚刚参加了测试，获得了', 320, 290);
                //   ctx.fillText(imgDetail.accuracy * 10 * 10 + '%的高正确率', 320, 336);
                // }
              // } else {
              //   ctx.fillText('我刚刚参加了个有趣的测试，', 320, 290);
              //   ctx.fillText('你也来试试！', 320, 336);
              // }
              // if (this.showVisitInlet) {
              //   ctx.font = "24px Microsoft YaHei";
              //   ctx.fillStyle = "#999999";
              //   ctx.textAlign = 'center'
              //   ctx.fillText('已经有' + imgDetail.allTestMan + '人参加过测试哟!快来瞧瞧！', 320, 230);
              // }
              ctx.fillStyle = "#222222";
              ctx.textAlign = 'left'
              let text = imgDetail.topicName;
              //绘制标题
              let titleArr = [];
              if (text.length > 0 && text.length <= 18) {
                let title1 = text.substring(0, 18);
                titleArr.push(title1);
              } else if (text.length > 18) {
                let title1 = text.substring(0, 18);
                let title2 = "";
                if (text.length <= 36) {
                  title2 = text.substring(18, 36);
                } else {
                  title2 = text.substring(18, 35);
                  title2 = title2 + "...";
                }
                titleArr.push(title1);
                titleArr.push(title2);
              }
              for (let i = 0; i < titleArr.length; i++) {
                //绘制简介文字
                let itemText = {
                  fontSize: 28,
                  fontColor: "#333333",
                  textAlign: that.isFromMutua && that.imgInfo.paperType == 3 ? "left" : "center",
                  textStr: titleArr[i],
                  offsetX: that.isFromMutua && that.imgInfo.paperType == 3 ? 110 : (c.width / 2),
                  offsetY: 754 + i * 43
                };
              ctx.fillStyle = "#999999";
                ctx.textAlign = 'center'
                that.drawText(ctx, itemText);
            }
              // }
              // for (let i = 1; getTrueLength(text) > 0; i++) {
              //   let tl = cutString(text, 42);
              //   ctx.fillText(text.substr(0, tl).replace(/^\s+|\s+$/, ""), 97, 650 + (i - 1) * 36, 446);
              //   text = text.substr(tl);
              // }

              ctx.font = "24px Microsoft YaHei";
              ctx.fillStyle = "#999999";
              ctx.textAlign = 'center'
              ctx.fillText('扫描二维码查看更多', 320, 996);
              convertCanvasToImage(ctx);
            };
            img2.onerror = function () {
              console.log("img2 err");
            }
            //      }
            img2.src = imgDetail.qrcodeUrl.indexOf("51ckjr.com") != -1 && imgDetail.qrcodeUrl.indexOf("http://") != -1 ? imgDetail.qrcodeUrl.replace("http://", "https://") : imgDetail.qrcodeUrl;//'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(imgDetail.mpQrcode)));
          };
          img1.onerror = function () {
            console.log("img1 err");
          }
          img1.src = imgDetail.avatar.includes('?') ? imgDetail.avatar + '&time=' + new Date().getTime() : imgDetail.avatar + '?time=' + new Date().getTime()
          // img1.src = imgDetail.avatar + '&time=' + new Date().getTime();//'https://knowledge-payment.oss-cn-beijing.aliyuncs.com/companies/2018-08-03/OYNUNvnjPikEcQldUBD4Me7E2PA7qyBqD8LdTm5S.jpeg?x-oss-process=style/common'//'https://knowledge-payment.oss-cn-beijing.aliyuncs.com/examTopic/2018-07-13/V4HTGrdfnBJwNCYm0RA3NPj7J7qzKv7Riar4HkWm.jpeg?x-oss-process=style/common';//require('../../../assets/timg.jpg');//imgDetail.avatar.indexOf("51ckjr.com") != -1 && imgDetail.avatar.indexOf("http://") != -1 ? imgDetail.avatar.replace("http://","https://") : imgDetail.avatar;
        }
        imgPeopleAvatar.onerror = function () {
          console.log("imgPeopleAvatar err");
        }
        let peopleAvatar = imgDetail.peopleAvatar;
        if (peopleAvatar) {
          let nowTimeTmp = Date.now();
          peopleAvatar = peopleAvatar.includes('?') ? `${peopleAvatar}&time=${nowTimeTmp}` : `${peopleAvatar}?time=${nowTimeTmp}`;
        } else {
          peopleAvatar = require('../../../assets/defult_head.png');
        }
        imgPeopleAvatar.src = peopleAvatar;
        console.log(imgPeopleAvatar.src)
      }
      imgBg.onerror = function () {
        console.log("imgBg err");
      }
      let bgSrc = require('../../../assets/i/wap/exam/bg-blue.png');
      if (!bgSrc.includes('base64')) {
        imgBg.crossOrigin = 'anonymous';
        let nowTimeTmp = Date.now();
        bgSrc = bgSrc.includes('?') ? `${bgSrc}&time=${nowTimeTmp}` : `${bgSrc}?time=${nowTimeTmp}`;
      }
      imgBg.src = bgSrc;

      function convertCanvasToImage(ctx) {
        try {
          var dataURL = ctx.canvas.toDataURL("image/jpeg");
          let ig = document.getElementById('spreadImg');
          ig.setAttribute("src", dataURL);
          //        console.log('convert');
        } catch (err) {
          console.log(err.message);
          console.log(err.stack);
        }
      }
      //获取字符串的真实长度（字节长度）
      // function getTrueLength(str) {
      //   let len = str.length;
      //   let truelen = 0;
      //   for (var x = 0; x < len; x++) {
      //     if (str.charCodeAt(x) > 128) {
      //       truelen += 2;
      //     } else {
      //       truelen += 1;
      //     }
      //   }
      //   return truelen;
      // }
      // //按字节长度截取字符串，返回substr截取位置
      // function cutString(str, leng) {
      //   let len = str.length;
      //   let tlen = len;
      //   let nlen = 0;
      //   for (let x = 0; x < len; x++) {
      //     if (str.charCodeAt(x) > 128) {
      //       if (nlen + 2 < leng) {
      //         nlen += 2;
      //       } else {
      //         tlen = x;
      //         break;
      //       }
      //     } else {
      //       if (nlen + 1 < leng) {
      //         nlen += 1;
      //       } else {
      //         tlen = x;
      //         break;
      //       }
      //     }
      //   }
      //   return tlen;
      // }
    },
    //绘制文字
    drawText(ctx, fontInfo) {
      ctx.font = fontInfo.fontSize + "px Microsoft YaHei";
      ctx.fillStyle = fontInfo.fontColor;
      ctx.textBaseline = "top";
      ctx.textAlign = fontInfo.textAlign;
      ctx.fillText(fontInfo.textStr, fontInfo.offsetX, fontInfo.offsetY, 600);
    },
    getImgs() {
      let $this = this;
      let urlT = '';
      if (this.topicId == 0) {
        urlT = global.apiurl + 'exam/shareExam/' + this.paperMainId + '?type=2&topicId=' + this.topicId
      } else {
        urlT = global.apiurl + 'exam/shareExam/' + this.paperMainId + '?topicId=' + this.topicId
      }
      utilJs.getMethod(urlT, function (res) {
        $this.imgInfo = res;
        $this.isInfo = res != null && res != '' ? false : true;
        if ($this.imgInfo.shareStyle == 2) {
          if ($this.imgInfo.shareCustomizeControl) {
              for (let i = 0; i < $this.imgInfo.shareCustomizeControl.length; i++) {
                $this.imgInfo.shareCustomizeControl[i].height = $this.imgInfo.shareCustomizeControl[i].height * 2 + 'px'
                $this.imgInfo.shareCustomizeControl[i].width = $this.imgInfo.shareCustomizeControl[i].width * 2 + 'px'
                $this.imgInfo.shareCustomizeControl[i].lineHeight = $this.imgInfo.shareCustomizeControl[i].lineHeight * 2 + 'px'
                $this.imgInfo.shareCustomizeControl[i].left = $this.imgInfo.shareCustomizeControl[i].posX * 2 + 'px'
                $this.imgInfo.shareCustomizeControl[i].top = $this.imgInfo.shareCustomizeControl[i].posY * 2 + 'px'
                $this.imgInfo.shareCustomizeControl[i].fontSize = $this.imgInfo.shareCustomizeControl[i].size * 2 + 'px'
                $this.imgInfo.shareCustomizeControl[i].letterSpacing = $this.imgInfo.shareCustomizeControl[i].letterSpacing * 2 + 'px'
              }
              document.ontouchstart = null;
              document.ontuchmove = null;
              document.ontouchend = null;
              $this.$nextTick(() => {
                $this.canvas();
              });
            }
        } else {
          $this.drawImg($this.imgInfo);
        }
      });
    },
    //将canvas转成图片
    canvasToImage(ctx) {
      try {
        var dataURL = ctx.canvas.toDataURL("image/jpg");
        let ig = document.getElementById("spreadImg");
        ig.setAttribute("src", dataURL);
      } catch (err) {
        console.log(err.message);
        console.log(err.stack);
      }
    },
    canvas() {
      let domTest = document.getElementById("canvas1");
      if (!domTest) {
        return;
      }
      html2canvas(domTest, {
        useCORS: true,
        height: domTest.offsetHeight, // 解决当前页面生成图片出现白边问题
        width: domTest.offsetWidth,
      }).then(canvas => {// eslint-disable-line
        // document.body.appendChild(canvas);
        let ctx = canvas.getContext("2d");
        this.canvasToImage(ctx);
      });
    },
    //分享
    wechatShare: function () {
      let title = this.examinationInfo.name;
      let shareImg = this.examinationInfo.avatar || require('../../../assets/examination_defult.png');
      let shareUrl = this.topicId == 0
        ? (
          this.isFromMutua
          ? `${window.location.href.split("#")[0]}#/homePage/mutuaTest/mutuaTestDetail?mutuaTestId=${this.paperMainId}&refereeId=${localStorage.getItem("userId")}`
          : `${window.location.href.split("#")[0]}#/homePage/testPaper/testDetail?testId=${this.paperMainId}&refereeId=${localStorage.getItem("userId")}`
        )
        : `${window.location.href.split("#")[0]}#/homePage/examination/examinationDetail?ExaminationNo=${this.topicId}&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = this.examinationInfo.shareDesc;//"共包含"+this.examinationInfo.hasPaper+"套考卷";
      this._shareUrl = shareUrl;
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc, function () { });
    },
    //手机端分享
    appShare: function () {
      let title = this.examinationInfo.name;
      let shareImg = this.examinationInfo.avatar || require('../../../assets/examination_defult.png');
      let shareUrl = this.topicId == 0
        ? (
          this.isFromMutua
          ? `${window.location.href.split("#")[0]}#/homePage/mutuaTest/mutuaTestDetail?mutuaTestId=${this.paperMainId}&refereeId=${localStorage.getItem("userId")}`
          : `${window.location.href.split("#")[0]}#/homePage/testPaper/testDetail?testId=${this.paperMainId}&refereeId=${localStorage.getItem("userId")}`
        )
        : `${window.location.href.split("#")[0]}#/homePage/examination/examinationDetail?ExaminationNo=${this.topicId}&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = this.examinationInfo.shareDesc;//"共包含"+this.examinationInfo.hasPaper+"套考卷";
      utilJs.appShareTrue(title, shareImg, shareUrl, shareDesc);
    }
  },
  activated() {
    setDocumentTitle("分享成绩");// eslint-disable-line
    this.paperMainId = this.$route.query.paperMainId;
    this.topicId = this.$route.query.topicId || '';
    this.isFromMutua = this.$route.query.isFromMutua ? true : false;
    this.showVisitInlet = this.$route.query.showVisitInlet ? true : false;
    this.enableShowScore = this.$route.query.enableShowScore;
    this.imgInfo = null;
    this.isInfo = false;
    let $this = this;
    if (this.topicId != 0) {
      utilJs.getMethod(global.apiurl + 'exam/topicDetail/' + this.topicId, function (res) {
        if (res.permission != 1) {
          $this.$routerGo($this, "push", {
            path: "/homePage/examination/examinationDetail",
            query: { ExaminationNo: $this.topicId }
          });
        }
        $this.examinationInfo = res.topicInfo;
        $this.wechatShare();
      });
    } else {
      utilJs.getMethod(
        global.apiurl + "paper/detail/" + this.paperMainId,
        res => {
          if (res.isGrounding == 0) {
            this.$routerGo(this, "replace", {
              path: "/error/emptyPage",
              query: {
                info: "很抱歉，该考试不存在"
              }
            });
          }
          if ((res.price * 1 > 0 && res.isGrounding == -1 && !res.permission) || (res.price * 1 == 0 && res.isGrounding == -1)) {
            this.$routerGo(this, "replace", {
              path: "/error/emptyPage",
              query: {
                info: '很抱歉，该考试已下架'
              }
            })
          }
          $this.examinationInfo = res
          this.wechatShare();
        }
      );
    }
    this.getImgs();
  },
  deactivated() {
    clearTimeout(this._touchTimeCon );
    this._touchTimeCon = null;
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.canvasBox {
  width: 640px;
  height: 1136px;
  top: -999999999px;
  left: -30000000px;
  z-index: -999;
  position: absolute;
}
.anvasContent {
  width: 640px;
  height: 1136px;
  position: relative;
}
.bgLocation {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}
</style>
